<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="130px" prop="msgTitle" label="消息标题:">
                    <el-input type="text" placeholder="请输入标题" v-model="postForm.msgTitle"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6">
                  <el-form-item label-width="130px" label="发布对象:" prop="selectedText">
                    <el-input
                      type="text"
                      placeholder="选择对象"
                      v-model="postForm.selectedText"
                      disabled
                      style="width:150px"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item style="margin-left:5px">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      @click="personSelectDialogVisible=true"
                    ></el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label-width="90px" label="级别:" prop="msgLevel">
                    <el-select v-model="postForm.msgLevel" placeholder="请选择等级">
                      <el-option label="一般" value="1"></el-option>
                      <el-option label="重要" value="2"></el-option>
                      <el-option label="紧急" value="3"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-col :span="10">
                  <el-form-item label-width="130px" label="完成时间:" prop="dispatchDate">
                    <el-date-picker
                      v-model="postForm.dispatchDate"
                      type="date"
                      value-format="yyyy/MM/dd"
                      placeholder="完成时间"
                      class="filter-item"
                    ></el-date-picker>
                  </el-form-item>
              </el-col>-->

              <!-- <el-col :span="8">
                  <el-form-item label-width="90px" label="类型:" class="postInfo-container-item">
                    <el-radio v-model="postForm.genre" label="1">消息</el-radio>
                    <el-radio v-model="postForm.genre" label="2">任务</el-radio>
                  </el-form-item>
              </el-col>-->
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="130px" label="消息内容:" prop="msgContent">
                    <el-input
                      type="textarea"
                      maxlength="1000"
                      show-word-limit
                      :rows="5"
                      placeholder="请输入消息内容"
                      v-model="postForm.msgContent"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <!-- <el-col width="100%">
                  <el-form-item label-width="80px" label="备注:" width="100%">
                    <el-input
                      type="textarea"
                      :rows="4"
                      maxlength="300"
                      show-word-limit
                      placeholder="请输入备注"
                      v-model="postForm.messageRemark"
                    ></el-input>
                  </el-form-item>
                </el-col>-->
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button type="primary" @click="submitForm">发布</el-button>
                    <el-button @click="closeCurrentTag">关闭</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-dialog title="用户对象" :visible.sync="personSelectDialogVisible" class="selectPerson">
      <div class="left">
        <fieldset class="fieldInfo">
          <legend>
            <span>组织机构树</span>
          </legend>
          <div class="tree">
            <el-tree
              ref="organizationTree"
              :data="organizationData"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              :props="defaultProps"
            ></el-tree>
          </div>
        </fieldset>
      </div>
      <div class="right">
        <fieldset class="fieldInfo">
          <legend>
            <span>所有人员</span>
          </legend>
          <div>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="checkedUserList" @change="handleCheckedCitiesChange">
              <el-checkbox
                v-for="(user,index) in userListOptions"
                :key="index"
                :label="user.id"
              >{{user.userName}}</el-checkbox>
            </el-checkbox-group>
          </div>
        </fieldset>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="personSelectDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmUsers">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { validURL } from '@/utils/validate'
import { addMessage } from '@/api/message'
import { searchUser } from '@/api/user'
import { fetchTreeData, fetchUserListByOrg } from '@/api/organization'
export default {
  name: 'MessageBasic',
  props: {
    isAdd: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const addMessage = {
      msgLevel: '', //等级
      msgContent: '', //消息内容
      msgTitle: '', //消息标题
      dipatcherIdList: [], //发布对象
      dispatchDate: '', //发布时间
      selectedText: ''
    }
    return {
      defaultProps: {
        label: 'name'
      },
      organizationData: [],
      isIndeterminate: true,
      checkAll: false,
      checkedUserList: [],
      personSelectDialogVisible: false, //用户选择对话框
      postForm: Object.assign({}, addMessage),
      loading: false,
      userListOptions: [],
      rules: {
        msgLevel: [
          { required: true, message: '消息级别不能为空', trigger: 'blur' }
        ],
        selectedText: [
          { required: true, message: '用户对象不能为空', trigger: 'blur' }
        ],
        msgTitle: [
          { required: true, message: '消息标题不能为空', trigger: 'blur' }
        ],
        msgContent: [
          { required: true, message: '消息内容不能为空', trigger: 'blur' }
        ],
        dispatchDate: [
          { required: true, message: '发布时间不能为空', trigger: 'blur' }
        ]
      },
      tempRoute: {}
    }
  },
  created() {
    this.getTreeData()
    if (this.isAdd) {
      const id = this.$route.params && this.$route.params.id
      // this.fetchData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    // 获取用户对象
    getRemoteUserList(orgId) {
      // this.personSelectDialogVisible = true
      fetchUserListByOrg(orgId).then((response) => {
        // if (!response.data.records) return
        this.userListOptions = response.data.map((v) => {
          return {
            id: v.id,
            userLoginAccount: v.userLoginAccount,
            userName: v.userName
          }
        })
        // console.log(this.userListOptions)
      })
    },
    handleNodeClick(data, node) {
      console.log(data, node)
      this.getRemoteUserList(data.id)
    },
    getTreeData() {
      fetchTreeData({
        rootId: 0
      }).then((response) => {
        console.log(response.data)
        this.organizationData = response.data
      })
    },
    handleCheckAllChange(val) {
      this.checkedUserList = val
        ? this.userListOptions.map((u) => {
            return u.id
          })
        : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.userListOptions.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.userListOptions.length
    },
    closeCurrentTag() {
      // 调用全局挂载的方法
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由
      this.$router.go(-1)
    },
    confirmUsers() {
      this.postForm.dipatcherIdList = this.checkedUserList
      this.postForm.selectedText = `已选择${this.checkedUserList.length}人`
      this.personSelectDialogVisible = false
    },
    // fetchData(id) {
    //   fetchMessage(id)
    //     .then((response) => {
    //       this.postForm = response.data

    //       // just for test
    //       //this.postForm.title += `   Article Id:${this.postForm.id}`
    //       this.postForm.content_short += `   Article Id:${this.postForm.id}`

    //       // set tagsview title
    //       this.setTagsViewTitle()

    //       // set page title
    //       this.setPageTitle()
    //     })
    //     .catch((err) => {
    //       console.log(err)
    //     })
    // },
    // setTagsViewTitle() {
    //   const title = '编辑'
    //   const route = Object.assign({}, this.tempRoute, {
    //     title: `${title}-${this.postForm.id}`
    //   })
    //   this.$store.dispatch('tagsView/updateVisitedView', route)
    // },
    // setPageTitle() {
    //   const title = '编辑'
    //   document.title = `${title} - ${this.postForm.id}`
    // },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          addMessage(this.postForm).then((res) => {
            if (res.success) {
              this.$notify({
                title: '成功',
                message: '消息发布成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '消息发布失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        } else {
          this.$notify({
            title: '失败',
            message: '消息发布验证失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    }
    // draftForm() {
    //   if (
    //     this.postForm.content.length === 0 ||
    //     this.postForm.title.length === 0
    //   ) {
    //     this.$message({
    //       message: '请填写必要的标题和内容',
    //       type: 'warning'
    //     })
    //     return
    //   }
    //   this.$message({
    //     message: '保存成功',
    //     type: 'success',
    //     showClose: true,
    //     duration: 1000
    //   })
    //   this.postForm.status = 'draft'
    // },
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';

.createPost-container {
  margin-top: 20px;
  position: relative;

  .createPost-main-container {
    padding: 5px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.selectPerson /deep/ .el-dialog__body {
  display: flex;
  .left {
    flex: 1;
  }
  .right {
    flex: 1;
  }
}
</style>
